from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.user import User
from app.models.schemas import (
    LoginRequest,
    Token,
    UserCreate,
    UserResponse,
    UserPasswordUpdate,
)
from app.services.auth_service import auth_service
from app.services.user_service import user_service
from app.utils.auth import verify_token

router = APIRouter()
security = HTTPBearer()


def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db),
) -> User:
    """获取当前用户"""
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )

    try:
        payload = verify_token(credentials.credentials)
        if payload is None:
            raise credentials_exception

        user_id: int = payload.get("user_id")
        if user_id is None:
            raise credentials_exception

    except Exception:
        raise credentials_exception

    user = user_service.get(db, user_id)
    print(f"DEBUG - User ID: {user.id}")
    print(
        f"DEBUG - is_superuser: {user.is_superuser} (type: {type(user.is_superuser)})"
    )
    print(f"DEBUG - is_active: {user.is_active}")
    if user is None:
        raise credentials_exception
    return user


def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
    """获取当前活跃用户"""
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="用户已被禁用")
    return current_user


@router.post("/register", response_model=UserResponse)
@router.post("/register", response_model=Token)
def register(user_data: UserCreate, db: Session = Depends(get_db)):
    """用户注册：创建用户并自动登录，返回 tokens"""
    result = auth_service.register(db, user_data=user_data)
    # auth_service.register 在正常流程下返回 {"user": user, "tokens": tokens}
    # 我们需要将 tokens 返回给前端以完成自动登录
    tokens = result.get("tokens")
    if not tokens:
        # 如果没有 tokens，则抛出服务器错误
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册成功，但无法创建令牌",
        )
    return tokens


@router.post("/login", response_model=Token)
def login(login_data: LoginRequest, db: Session = Depends(get_db)):
    """用户登录"""
    result = auth_service.login(db, login_data=login_data)
    return result["tokens"]


@router.post("/refresh", response_model=Token)
def refresh_token(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db),
):
    """刷新令牌"""
    result = auth_service.refresh_token(db, refresh_token=credentials.credentials)
    return result["tokens"]


@router.get("/profile", response_model=UserResponse)
def get_current_user_info(current_user: User = Depends(get_current_active_user)):
    """获取当前用户信息"""
    return current_user


@router.put("/change-password")
def change_password(
    password_data: UserPasswordUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """修改密码"""
    result = auth_service.change_password(
        db,
        user=current_user,
        current_password=password_data.current_password,
        new_password=password_data.new_password,
    )
    return result


@router.post("/logout")
def logout(
    credentials: HTTPAuthorizationCredentials = Depends(security),
    db: Session = Depends(get_db),
):
    """用户退出登录"""
    # 不验证token是否过期，只要有token就尝试解析并退出登录
    from app.utils.auth import verify_token
    from jose import jwt, JWTError
    from app.utils.config import settings

    try:
        # 尝试解析token，即使过期也能获取到用户信息
        payload = jwt.decode(
            credentials.credentials,
            settings.SECRET_KEY,
            algorithms=[settings.ALGORITHM],
            options={"verify_exp": False},  # 忽略过期时间验证
        )
        user_id = payload.get("user_id")

        if user_id:
            # 如果能解析到用户ID，则调用logout服务
            # 这里不需要验证用户是否存在或激活，因为只是退出登录
            result = auth_service.logout(
                db, user_id=user_id, token=credentials.credentials
            )
            return result
    except JWTError:
        # token完全无效也没关系，返回成功消息
        pass

    # 无论如何都返回退出成功的消息
    return {"message": "退出登录成功", "detail": "令牌已处理，请重新登录"}
